<template>
  <a-card :bordered="false">
    <div class="layout-wrap">
      <div class="nav-box">
        <a-tabs v-model="type" tab-position="left" @change="searchReset">
          <a-tab-pane v-for="(name, type) in tabs" :key="type" :tab="name" />
        </a-tabs>
      </div>
      <div class="content-box">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <div class="module-title">{{ tabs[type] }}字典值</div>
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :md="6" :sm="12">
                <a-form-item label="名称">
                  <a-input placeholder="请输入名称" v-model="queryParam.name" :maxLength="20"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="12">
                <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQueryClick" icon="search">查询</a-button>
                  <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <a-button
            v-has="'ArchiveBasicDataSet:add'"
            type="primary"
            icon="plus"
            @click="
              editId = ''
              showEditModal = true
            "
            >新增</a-button
          >
        </div>
        <!-- table区域-begin -->
        <a-table
          size="middle"
          bordered
          rowKey="id"
          ref="table"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="false"
          :loading="loading"
          @change="handleTableChange"
        >
          <div v-has="'ArchiveBasicDataSet:edit'" slot="sortSlot">
            <a-icon v-show="!tableSort && !isFilter" type="menu" class="sort-handler-ico" title="拖动排序" />
            <a-icon v-show="tableSort || isFilter" type="disconnect" class="sort-disable-ico" title="请重置后排序" />
          </div>
          <span slot="action" slot-scope="text, record">
            <a v-has="'ArchiveBasicDataSet:edit'" @click="editReady('edit', record.id)">编辑</a>

            <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
              <a-menu slot="overlay">
                <a-menu-item v-has="'ArchiveBasicDataSet:del'">
                  <a @click="editReady('del', record.id)">删除</a>
                </a-menu-item>
                <a-menu-item v-has="'ArchiveBasicDataSet:log'">
                  <j-operate-log :id="record.id" />
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </span>
        </a-table>
      </div>
    </div>
    <basic-data-modal
      v-if="showEditModal"
      :visible.sync="showEditModal"
      :editType="type"
      :editId="editId"
      :tabs="tabs"
      :sortNum="dataSource.length + 1"
      @submit="searchReset"
    />
  </a-card>
</template>

<script>
import Sortable from 'sortablejs'
import { deleteAction, getAction, postAction } from '@/api/manage'

import BasicDataModal from './modules/BasicDataModal.vue'

export default {
  name: 'BasicDataSet',
  components: {
    BasicDataModal,
  },
  data() {
    return {
      tabs: {
        Halt: '停售原因',
        Type: '产品分类',
        Material: '产品材质',
        Level: '产品等级',
        InfringementLevel: '侵权等级',
        Attribute: '产品属性',
      },

      editId: '', //  要编辑或查看的产品档案id，为空表示新增
      showEditModal: false, // 是否展示编辑弹窗
      dataSource: [],
      type: 'Halt',
      loading: false,
      tableSort: false, // 是否开启了表格列排序
      isFilter: false, // 是否开启了筛选(输入筛选项进行搜索)
      queryParam: {
        name: '',
      },
    }
  },
  computed: {
    columns() {
      return [
        {
          title: '排序',
          width: 60,
          align: 'center',
          scopedSlots: { customRender: 'sortSlot' },
        },
        {
          title: '序号',
          width: 60,
          align: 'center',
          dataIndex: 'sortNum',
        },
        {
          title: '名称',
          align: 'left',
          dataIndex: 'name',
        },
        {
          title: '编号',
          align: 'center',
          dataIndex: 'code',
        },
        {
          title: '变更时间',
          align: 'center',
          dataIndex: 'updateTime',
          sorter: true,
          sortOrder: this.tableSort,
          customRender(text, record) {
            return record.updateTime ? record.updateTime + ' ' + record.updateBy : record.createTime + ' ' + record.createBy
          },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ]
    },
    url() {
      return {
        delete: `/hzkj-product/product/archive/archive${this.type}Data/delete`,
        list: `/hzkj-product/product/archive/archive${this.type}Data/list`,
        sort: `/hzkj-product/product/archive/archive${this.type}Data/editSort`,
        allowEdit: `/hzkj-product/product/archive/archive${this.type}Data/allowEdit`,
      }
    },
  },
  methods: {
    // 表格自带排序功能
    handleTableChange(pagination, filters, sorter) {
      this.tableSort = sorter.order
      if (sorter.order) {
        this.dataSource = this.dataSource.sort((a, b) => {
          let aNum = a.updateTime ? new Date(a.updateTime).getTime() : 0
          let bNum = b.updateTime ? new Date(b.updateTime).getTime() : 0
          if (sorter.order == 'ascend') {
            return aNum - bNum
          } else if (sorter.order == 'descend') {
            return bNum - aNum
          }
        })
      } else {
        this.searchQuery()
      }
    },
    searchQueryClick() {
      this.isFilter = true // 开启筛选
      this.searchQuery()
    },
    searchQuery() {
      this.loading = true
      this.tableSort = false // 重置表格排序状态
      getAction(this.url.list, {
        pageNo: 1,
        pageSize: 1000,
        ...this.queryParam,
      })
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records.sort((a, b) => {
              return a.sortNum - b.sortNum // 按照sortNum排序
            })
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    searchReset() {
      this.isFilter = false // 关闭筛选
      this.queryParam.name = ''
      this.searchQuery()
    },
    handleDelete(id) {
      deleteAction(this.url.delete, { id: id }).then((res) => {
        if (res.success) {
          this.searchQuery()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    editReady(type, id) {
      getAction(this.url.allowEdit, { id }).then((res) => {
        if (res.result == 0) {
          if (type == 'edit') {
            this.editId = id
            this.showEditModal = true
          } else if (type == 'del') {
            this.$confirm({
              content: (h) => {
                return h(
                  'div',
                  {
                    domProps: {
                      innerHTML: `<div style="padding-left: 40px;">删除后查询条件不显示且不可恢复，是否确定删除？</div>`,
                    },
                  },
                  []
                )
              },
              onOk: () => {
                this.handleDelete(id)
              },
            })
          }
        } else {
          this.$message.warning('该属性已被产品档案引用，不能修改')
        }
      })
    },
  },
  created() {
    // 初始化查询
    this.searchQuery()
  },
  mounted() {
    //初始化表格拖动
    this.$nextTick(() => {
      new Sortable(this.$refs.table.$el.querySelector('tbody'), {
        handle: '.sort-handler-ico',
        animation: 200,
        sort: true,
        onEnd: ({ newIndex, oldIndex }) => {
          //  oldIndex:谁
          //  newIndex:移动到哪儿
          const currRow = this.dataSource.splice(oldIndex, 1)[0]
          this.dataSource.splice(newIndex, 0, currRow)
          postAction(
            this.url.sort,
            this.dataSource.map((item, index) => ({
              id: item.id,
              sortNum: index + 1, // 确保排序号从1开始
            }))
          ).then((res) => {
            if (res.success) {
              this.$message.success('排序成功')
              this.searchQuery()
            } else {
              this.$message.error(res.message)
            }
          })
        },
      })
    })
  },
}
</script>

<style lang="less" scoped>
.layout-wrap {
  display: flex;
  align-items: flex-start;
}
.nav-box {
  width: 110px;
  flex-shrink: 0;
}

.content-box {
  flex-grow: 1;
  padding: 15px;
}

.sort-handler-ico {
  padding: 10px;
  cursor: move;
}
.sort-disable-ico {
  padding: 10px;
  cursor: no-drop;
}

.module-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
}
</style>
